<?php
class KolSys_Curl
{
	private $ch,$options;
	public function init()
	{
		$this->ch=curl_init();
		$this->options=array();
		$this->options[CURLOPT_MAXREDIRS]=3;
		$this->options[CURLOPT_FOLLOWLOCATION]=true;
		$this->options[CURLOPT_HEADERFUNCTION]='KolSys_Curl_Header::read_header';
		$this->options[CURLOPT_RETURNTRANSFER]=true;
		$this->headers=array();
		$this->debugMode=false;
		$this->outputResponseHeader=false;
		
	}

	public function setOption($option,$value)
	{
		$this->options[$option]=$value;
	}

	public function setDebugMode($value)
	{
		$this->debugMode=$value;
	}
	

	public function getOptions()
	{
		return $this->options;
	}

	public function setCookie($value)
	{
		$this->setOption(CURLOPT_COOKIE,$value);
	}

	public function dispatch()
	{
		foreach($this->options as $key=>$value){curl_setopt($this->ch,$key,$value);}
		if(sizeof($this->headers))
		{
			curl_setopt($this->ch,CURLOPT_HTTPHEADER,$this->headers);
		}

		if($this->debugMode){
			//curl_setopt($this->ch, CURLOPT_HEADER, 1);
			curl_setopt($this->ch, CURLINFO_HEADER_OUT, true);
		}

		$result=curl_exec($this->ch);
		if($this->debugMode){print_readable(curl_getinfo($this->ch));}
		curl_close($this->ch);
		if($this->outputResponseHeader)
		{
			list($header,$body)=explode("\r\n\r\n",$result,2);
			return array($header,$body,'header'=>$header,'body'=>$body);
		}
		return $result;
	}

	public function setURL($url)
	{
		$this->setOption(CURLOPT_URL, $url);
	}
	public function setUserAgent($str)
	{
		$this->setOption(CURLOPT_USERAGENT, $str);
	}
	public function setReferer($str)
	{
		$this->setOption(CURLOPT_REFERER, $str);
	}
	public function setTimeout($num)
	{
		$this->setOption(CURLOPT_TIMEOUT, $num);//The maximum number of seconds to allow cURL functions to execute.
	}
	public function setPostData($str)
	{
		$this->setOption(CURLOPT_POST, 1);
		$this->setOption(CURLOPT_POSTFIELDS, $str);
	}

	public function addHeader($nameAndValue)
	{
		$this->headers[]=$nameAndValue;
	}

}